package com.i2863.sso;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.i2863.sso.util.HttpSessionUtils;
import com.i2863.sso.util.MD5Utils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xuweiwei on 2017/8/21.
 */
public class UcenterAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {

    private String ucenter;
    CloseableHttpClient httpClient = HttpSessionUtils.buildHttpClient();

    @Override
    protected boolean authenticateUsernamePasswordInternal(UsernamePasswordCredentials credentials) throws AuthenticationException {
        final String username = credentials.getUsername();
        final String password = credentials.getPassword();

        String md5Password = MD5Utils.encrypt(password);
        Map<String, String> param = new HashMap<String, String>();
        param.put("method", "login");
        param.put("username", username);
        param.put("password", md5Password);
        param.put("siteId", "127");
        try {
            String json = HttpSessionUtils.httpPost(httpClient, ucenter, param);
            JSONObject jsonObject = JSON.parseObject(json);
            int code = jsonObject.getInteger("code");
            if (code == 0) {
                log
                        .info("User [" + username
                                + "] was successfully authenticated.");
                return true;
            } else {
                log.info("User [" + username
                        + "] was failed authentication.");
            }
        } catch (IOException e) {
            log.error("User [" + username
                    + "] login error.", e);
        }

        return false;
    }

    public String getUcenter() {
        return ucenter;
    }

    public void setUcenter(String ucenter) {
        this.ucenter = ucenter;
    }

    public static void main(String[] args) throws AuthenticationException {
        UcenterAuthenticationHandler ucenterAuthenticationHandler = new UcenterAuthenticationHandler();
        ucenterAuthenticationHandler.setUcenter("http://ucenter.i2863.com/interface");
        UsernamePasswordCredentials  c = new UsernamePasswordCredentials();
        c.setUsername("13980974244");
        c.setPassword("123456");
        ucenterAuthenticationHandler.authenticateUsernamePasswordInternal(c);
    }
}
